<?php

if(STAINLESS != 1){
	require_once('../config.php');
	redirect("$home_url/admin/login/");
}

if(isset($_POST['request_add'])){

	$params = array(
		'name'		=> trim($_POST['product_name']),
		'category'	=> $_POST['product_category'],
		'photo'		=> $_FILES['product_photo']['name'],
		'price'		=> trim($_POST['product_price']),
		'link'		=> trim($_POST['product_link'])
	);
	if(!validate($params['price'],DATA_NUMERIC)){
		$notice="only_numeric";
	}elseif($params['name'] && $params['category'] && $params['link']){
	
		$db = new models($host,$user,$pass,$db_name);
		$params['name'] = preg_replace("/[\/\'\"]/","",$params['name']);
		$db->where("name='" . $params['name'] . "' OR link = '".$params['link']."'");
		$pr_check = $db->get_data("products");
		
		if($pr_check){
			$notice="duplicate";
		}else{
		
			if($_FILES['product_photo']['name']){
				$check = getimagesize($_FILES['product_photo']['tmp_name']);
				if($check !== false){
					if($check['mime'] == 'image/jpg' || $check['mime'] == 'image/jpeg' || $check['mime'] == 'image/png' || $check['mime'] == 'image/gif'){
						if($_FILES['product_photo']['size'] < 1048576){
							$path = HOME_DIR . "/images/photos/";
							$name_photo = unicode_convert(strtolower($params['name']));
							$name_photo = str_replace(" ","-",$name_photo) . "." . substr($check['mime'],6);
							$params['photo'] = $name_photo;
							$uploadOK = move_uploaded_file($_FILES['product_photo']['tmp_name'],$path.$name_photo);
							if(!$uploadOK){
								$notice="upload_error";
							}
						}else{
							$notice="limit_size_image";
						}
					}else{
						$notice="only_image";
					}
				}else{
					$notice="only_image";
				}
			}elseif($_POST['product_photo_url'] != ''){
			
				require_once(HOME_DIR . "/libraries/image.php");
				$source_url = $_POST['product_photo_url'];
				$name_photo = unicode_convert(strtolower($params['name'])) . ".jpg";
				$name_photo = str_replace(" ","-",$name_photo);
				$destination_url = HOME_DIR . "/images/photos/$name_photo";
				$resizeObj = new resize($source_url);
				$resizeObj -> resizeImage(200, 200, 'auto');//options: exact, portrait, landscape, auto, crop
				$resizeObj -> saveImage($destination_url, 100);
				$params['photo'] = $name_photo;
			}
		
			$db->insert("products",$params);
			$notice="success";
		}
	}else{
		$notice="require";
	}
	redirect("$home_url/admin/products/?notice=$notice");
}